﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：吕海乐 
    //
    // 文件名：RelationHospitalEdit.cs
    // 文件功能描述：管理需配送的医疗机构
    // 创建标识：吕海乐2009-04-13
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
// 审核时间：
// 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HZ.DrugTrade.Model;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.BLLFactory;
using System.Data;
using HZ.DrugTrade.Model.Enum;

namespace HZ.DrugTrade.Web.Admin.DistributionManage
{
    public partial class RelationHospitalEdit : BasePage
    {
        public RelationHospitalEdit()
        {
            this.ModuleNo = Module.配送关系管理.ToString();
        }

        IBLL_Company ic = Factory.BLL_Company();
        IBLL_User iu = Factory.BLL_User();
        IBLL_Distribution id = Factory.BLL_Distribution();
        IBLL_Area ia = Factory.BLL_Area();

        DataTable _AreaHospitalTable;
        protected void Page_Load(object sender, EventArgs e)
        {
            string procureCatalogId = Request.QueryString["procureCatalogId"];
            string companyId = Request.QueryString["companyId_PS"];
            if (string.IsNullOrEmpty(procureCatalogId) || string.IsNullOrEmpty(companyId))
            {
                PageError("参数错误！", this.ReturnUrl);
            }

            if (!IsPostBack)
            {
                //获取企业基本信息
                int totalCount = 0;
                Company company = ic.GetCompanyByWhere(new HZ.DrugTrade.Model.Query.Company() { CompanyID = companyId }, 1, 0, out totalCount)[0];
                txtCompanyName.Text = company.CompanyName;
                //绑定医疗机构
                BindHospital();

                //此处调用目的，为了设置DropdownList的状态
                GetDefaultAreaString();
            }
        }

        private void BindHospital()
        {
            //获取所有符合条件（已入围、医疗机构已启用该采购目录）的医疗机构
            HZ.DrugTrade.Model.Query.AreaHospitalProcureCatalo qHospital = new HZ.DrugTrade.Model.Query.AreaHospitalProcureCatalo();
            qHospital.ProcureCatalogID = Request.QueryString["procureCatalogId"];
            qHospital.AreaID = GetAreaID();
            qHospital.IsUsing = true;
            qHospital.SortFields = "HospitalID";
            //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;
            int totalCount = 0;
            IList<HZ.DrugTrade.Model.View.AreaHospitalProcureCatalo> hospitalList = id.GetAreaHospitalProcureCatalogByWhere(qHospital, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalCount);
            DataTable allHospital = HZ.Data.ModelConvert.GetDataTableFromModel(hospitalList);

            //该配送企业已存在的医疗机构
            HZ.DrugTrade.Model.Query.DistributionRelation qDistributionRelation = new HZ.DrugTrade.Model.Query.DistributionRelation();
            qDistributionRelation.ProcureCatalogID = Request.QueryString["procureCatalogId"];
            qDistributionRelation.CompanyID_PS = Request.QueryString["companyId_PS"];
            qDistributionRelation.SortFields = "CompanyName_PS asc";
            IList<HZ.DrugTrade.Model.View.DistributionRelation> distibutionRelationList = id.GetDistributionByWhere(qDistributionRelation, 1, 0, out totalCount);
            DataTable existHospital = HZ.Data.ModelConvert.GetDataTableFromModel(distibutionRelationList);

            //合并两张表格
            for (int i = allHospital.Rows.Count-1; i >= 0; i--)
            {
                for (int j = 0; j < existHospital.Rows.Count; j++)
                {
                    if (allHospital.Rows[i]["HospitalID"].Equals(existHospital.Rows[j]["HospitalID"]))
                    {
                        allHospital.Rows[i].Delete();
                        break;
                    }
                }
            }

            _AreaHospitalTable = allHospital.DefaultView.ToTable();
            gvwHospital.DataSource = _AreaHospitalTable;
            gvwHospital.DataBind();
        }

        /// <summary>
        /// 获取地区查询条件 AreaID
        /// </summary>
        /// <returns></returns>
        private string GetAreaID()
        {
            string areaId = "";

            //首次进入使用当前用户所在区域ID
            areaId = CurrentAccount.GetUser().Org.Area.AreaID;

            //优先获取区县，其次城市，再次省份
            if (new Common.ConvertHelper(Request.Form["ctl00$ContentPlaceHolder1$ddlCountry"]).String != Constants.ALL_ITEM_VALUE)
            {
                areaId = Request.Form["ctl00$ContentPlaceHolder1$ddlCountry"];
            }
            else
            {
                if (new Common.ConvertHelper(Request.Form["ctl00$ContentPlaceHolder1$ddlCity"]).String != Constants.ALL_ITEM_VALUE)
                {
                    areaId = Request.Form["ctl00$ContentPlaceHolder1$ddlCity"];
                }
                else if (new Common.ConvertHelper(Request.Form["ctl00$ContentPlaceHolder1$ddlProvice"]).String != Constants.ALL_ITEM_VALUE)
                {
                    areaId = Request.Form["ctl00$ContentPlaceHolder1$ddlProvice"];
                }

            }
            return areaId;
        }

        /// <summary>
        /// 保存医疗机构
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            string procureCatalogId = Request.QueryString["procureCatalogId"];
            string companyId = Request.QueryString["companyId_PS"];
            string hospitalIds = Request["chkHospital"];
            List<DistributionRelation> distributionList = new List<DistributionRelation>();
            if (!string.IsNullOrEmpty(hospitalIds))
            {
                string[] arrayIds = hospitalIds.Split(',');
                foreach (string item in arrayIds)
                {
                    DistributionRelation distributionRelation = new DistributionRelation();
                    distributionRelation.ProcureCatalogID = procureCatalogId;
                    distributionRelation.CompanyID_PS = companyId;
                    distributionRelation.HospitalID = item;
                    distributionList.Add(distributionRelation);
                }
            }
            else
            {
                PageError("未选中任何医疗机构！", Request.RawUrl);
            }

            if (id.AddDistributionByProcureCatalogCompany_Batch(distributionList, new DistributionRelation() { ProcureCatalogID=procureCatalogId,CompanyID_PS=companyId}) == 1)
            {
                PageInfo("保存成功！", this.ReturnUrl);
            }
            else
            {
                PageError("保存失败！", this.ReturnUrl);
            }
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            BindHospital();
        }

        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            BindHospital();
        }

        /// <summary>
        /// 获取默认选中的地区编号串
        /// 供JS函数使用
        /// </summary>
        /// <returns></returns>
        protected string GetDefaultAreaString()
        {
            //默认城市 江苏省 320000
            string defaultProvince = "320000";
            string defaultCity = "";
            //
            string strArea = "";

            //获取当前用户所在区域
            IBLL_Area areaCtrl = Factory.BLL_Area();
            Area area = areaCtrl.GetArea(CurrentAccount.GetUser().Org.Area.AreaID);

            //如果是市级中心机构，则默认选中具体城市
            if (area.FatherAreaID != "0")
            {
                defaultProvince = area.FatherAreaID;
                defaultCity = area.AreaID;
            }
            else
            {
                defaultProvince = area.AreaID;
            }

            //显示默认地区，范围之外的内容禁止选择
            strArea += "," + "\"" + defaultProvince + "\"";
            this.ddlProvice.Enabled = false;
            if (!string.IsNullOrEmpty(defaultCity))
            {
                strArea += "," + "\"" + defaultCity + "\"";
                this.ddlCity.Enabled = false;
            }
            else if (!string.IsNullOrEmpty(Request.Form["ctl00$ContentPlaceHolder1$ddlCity"]))
            {
                strArea += "," + "\"" + Request.Form["ctl00$ContentPlaceHolder1$ddlCity"] + "\"";
            }

            if (!string.IsNullOrEmpty(Request.Form["ctl00$ContentPlaceHolder1$ddlCountry"]))
            {
                strArea += "," + "\"" + Request.Form["ctl00$ContentPlaceHolder1$ddlCountry"] + "\"";
            }

            return strArea;
        }
    }
}
